package com.lp.model.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lp.model.constants.HeaderConstants;
import com.lp.model.constants.RedisConstants;
import com.lp.model.entity.user.User;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.servlet.http.HttpServletRequest;

public class UserUtils {

    /**
     * 通过 token 获取 当前登录用户信息
     */
    public static User getUserByToken(StringRedisTemplate redisTemplate, ObjectMapper objectMapper,
                                      HttpServletRequest request) {
        String token = request.getHeader(HeaderConstants.TOKEN);
        String userJson = redisTemplate.opsForValue().get(RedisConstants.TOKEN + token);
        User user = null;
        try {
            user = objectMapper.readValue(userJson, User.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return user;
    }

}
